<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/24
 * Time: 9:43
 */

namespace app\admin\controller;


use app\common\controller\AdminBase;
use think\Db;
use think\Loader;
use think\Request;

class Pages extends AdminBase
{
    public function index()
    {
        $chk = check_juri(request()->controller(), 'index', $this->_juri);
        if ($chk['status'])
        {
            $list = Db::name('pages')
                ->alias('p')
                ->field('p.id, p.category_id, p.title, p.thumb, p.author, p.description, p.update_time, c.title as category')
                ->join('__CATEGORY__ c', 'p.category_id = c.id')
                ->order('p.create_time desc')
                ->select();
            return view('index', [
                'list'=>$list
            ]);
        } else {
            $this->error($chk['msg'], url('admin/index/index'), 3);
        }
    }

    public function edit()
    {
        $chk = check_juri(request()->controller(), 'edit', $this->_juri);
        if ($chk['status'])
        {
            $id = intval(input('param.id'));
            $info = Db::name('pages')
                ->field('id, title, other_title, thumb, keywords, description, author, source, hits, content, photos, enclosure')
                ->where('id = '. $id)
                ->find();
            $info['photos'] = json_decode($info['photos'], true);
            $info['enclosure'] = json_decode($info['enclosure'], true);
            return view('edit', [
                'info'=>$info
            ]);
        } else {
            $this->error($chk['msg'], url('admin/index/index'), 3);
        }
    }

    public function doEdit()
    {
        if (request()->isPost())
        {
            $data   = Request::instance()->post();
            $cate   = Db::name('Pages')->field('thumb')->where('id', $data['id'])->find();
            $result = $this->validate($data, 'Pages');
            if ($result !== true)
            {
                return ['status'=>false, 'msg'=>$result];
            }
            $info   = img_upload_one('thumb');
            if ($info)
            {
                if ($info['status'])
                {
                    $path          = './public/'.$cate['thumb'];
                    if (file_exists($path))
                    {
                        @unlink($path);
                    }
                    $data['thumb'] = $info['msg'];
                } else {
                    return ['status'=>false, 'msg'=>$info['msg']];
                }
            } else {
                if (isset($data['thumb_del']))
                {
                    $data['thumb'] = '';
                } else {
                    $data['thumb'] = $cate['thumb'];
                }
            }
            $system = Loader::model('Pages');
            $system->edit($data);
            return ['status'=>true, 'msg'=>$data];
        }
    }
}